'use strict';

const db = uniCloud.database()
const uniIdCommon = require('uni-id-common')

exports.main = async (event, context) => {
  // 管理员访问
  const isAdminAccess = event.isAdmin || false
  
  // 1. 获取 token
  const token = context.uniIdToken || event.uniIdToken || (event.args && event.args.uniIdToken)
  if (!token) {
    return { code: 401, msg: '未登录' }
  }
  
  // 2. 解析 token
  const uniId = uniIdCommon.createInstance({ context })
  const tokenRes = await uniId.checkToken(token)
  if (tokenRes.code !== 0) {
    return { code: 401, msg: 'token无效或已过期' }
  }
  const uid = tokenRes.uid

  // 3. 构建筛选条件
  const { status, keyword, page = 1, pageSize = 20, startTime, endTime } = event
  let where = {}
  
  // 管理员可以查看所有记录，普通用户只能查看自己的
  if (!isAdminAccess) {
    where.user_id = uid
  }
  
  if (status) {
    where.status = status
  }

  // 关键词搜索
  if (keyword) {
    where = db.command.or([
      { payment_id: new RegExp(keyword, 'i') },
      { original_payment_id: new RegExp(keyword, 'i') },
      { refund_reason: new RegExp(keyword, 'i') }
    ])
    if (!isAdminAccess) {
      where = db.command.and([
        { user_id: uid },
        where
      ])
    }
  }

  // 时间范围查询
  if (startTime && endTime) {
    where.create_time = db.command.gte(new Date(startTime)).and(db.command.lte(new Date(endTime)))
  }

  try {
    // 4. 查询退款记录
    const countResult = await db.collection('refund_records').where(where).count()
    const total = countResult.total
    
    const skip = (page - 1) * pageSize
    let query = db.collection('refund_records')
      .where(where)
      .orderBy('create_time', 'desc')
      .skip(skip)
      .limit(pageSize)

    // 联查支付记录和用户信息
    if (isAdminAccess) {
      query = query.lookup({
        from: 'payment_records',
        localField: 'payment_id',
        foreignField: '_id',
        as: 'payment_info'
      }).lookup({
        from: 'uni-id-users',
        localField: 'user_id',
        foreignField: '_id',
        as: 'user_info'
      })
    } else {
      query = query.lookup({
        from: 'payment_records',
        localField: 'payment_id',
        foreignField: '_id',
        as: 'payment_info'
      })
    }

    const res = await query.get()
    let data = res.data

    // 处理关联数据
    data = data.map(item => ({
      ...item,
      payment_info: item.payment_info && item.payment_info[0] ? item.payment_info[0] : null,
      user_info: isAdminAccess && item.user_info && item.user_info[0] ? {
        nickname: item.user_info[0].nickname,
        avatar: item.user_info[0].avatar
      } : null
    }))

    return {
      code: 200,
      data: {
        records: data,
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize)
      }
    }
  } catch (error) {
    console.error('查询退款记录失败:', error)
    return {
      code: 500,
      msg: '查询失败',
      data: null
    }
  }
}
